using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
[Authorize]
public class CustomersController : ODataController
{
    private SampleContext _db;
    public CustomersController(SampleContext context)
    {
        _db = context;
    }
    private bool CustformExists(int key)
    {
        return _db.Customers.Any(p => p.CustformId == key);
    }
    [HttpPut]
    public async Task<IActionResult> Put([FromODataUri] int key, [FromBody]Custform update)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        if (key != update.CustformId)
        {
            return BadRequest();
        }
        //update.Company = _db.Companies.FirstOrDefault(e=>e.CompanyId==update.CompanyId);
        _db.Entry(update).State = EntityState.Modified;
        try
        {
            await _db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CustformExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        return Updated(update);
    }
    public async Task<IActionResult> Delete([FromODataUri] int key)
    {
        var admin = await _db.Customers.FindAsync(key);
        if (admin == null)
        {
            return NotFound();
        }
        _db.Customers.Remove(admin);
        await _db.SaveChangesAsync();
        return NoContent();
    }
    [EnableQuery]
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] Custform model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("无效数据");
        }
        //_db.Companies.Attach(model.Company);
        _db.Customers.Add(model);
        await _db.SaveChangesAsync();
        return Created(Request.Path,model);
    }
    [EnableQuery]
    public IActionResult Get()
    {
        return Ok(_db.Customers);
    }
    //
}